import {Component, OnInit, ViewChild} from '@angular/core';
import {Router} from '@angular/router';
import {RoleService} from '../../../lib/service/admin/role.service';
import {RoleList, RoleInfo, AddRole, EditRole} from "./role";
import {ModalDirective} from 'ngx-bootstrap';
import {TreeData} from '../p-tree/tree-model';
import {PTreeComponent} from "../p-tree/p-tree.component";

@Component({
  selector: 'app-role',
  templateUrl: './role.component.html',
  styleUrls: ['./role.component.scss']
})
export class RoleComponent implements OnInit {

  totalItems: number;
  currentPage = 1;
  itemsPerPage = 12;
  name: string;
  belong: string;
  orderField: string;
  orderSort: string;
  type: string;
  message: string;
  isShow = false;
  roleInfo = new RoleInfo();
  roleList = new RoleList();
  addRole = new AddRole();
  editRole = new EditRole();
  setId: number;
  permissionGroup = [];
  permissionCheck: any = [];
  permissionList: any = [];

  @ViewChild('t') t: PTreeComponent;

  singleCheckedNodeId: string = '2';
  // permissionGroup: any;
  ids = [];
  p_list = [];

  @ViewChild('addModal') public addModal: ModalDirective;
  @ViewChild('editModal') public editModal: ModalDirective;
  @ViewChild('staticModal') public staticModal: ModalDirective;

  constructor(private router: Router,
              private roleService: RoleService) {
    this.name = '';
    this.belong = '';
    this.orderField = '';
    this.orderSort = '';
  }

  ngOnInit() {
    this.getRoleList();
  }

  onClick(item) {
    console.info(item);
  }


  checkednum = 0;

  checkNumCount(arr) {
    arr.map((e) => {
      ++this.checkednum;
      console.log(e.isChecked);
      if(e.isChecked) {
        this.ids.push(e.id);
      }
      if(e.children) {
        this.checkNumCount(e.children);
      }
    });
  }
  onCheckChanged() {
    this.checkednum = 0;
    this.ids = [];
    this.checkNumCount(this.p_list);
    // console.log(this.checkednum,this.ids);
    // if(this.checkednum == 67) {
    //   console.log(this.checkednum,this.ids);
    // }
    // if (item.isChecked) {
    //   this.ids = this.ids.filter((v, i, arr) => {
    //     return v != item.id;
    //   })
    // } else {
    //   if (this.ids.length === 0) {
    //     this.ids.push(item.id);
    //   } else {
    //     let flag = true;
    //     this.ids.every((v, i, arr) => {
    //       if (v == item.id) {
    //         flag = false;
    //       }
    //       return true;
    //     });
    //     if (flag) {
    //       this.ids.push(item.id);
    //     }
    //   }
    // }
    // console.log('ids',this.ids);
  }

  /*获取角色列表*/
  getRoleList(): void {
    this.roleService.getRoleList(this.name, this.belong, this.orderField, this.orderSort, this.currentPage, this.itemsPerPage).subscribe(
      data => {
        if (data.code === 2000) {
          this.roleList.list = data.data.data;
          this.currentPage = data.data.currentPage;
          this.totalItems = data.data.total;
        }
      }
    );
  }

  /*角色详情*/
  getRoleInfo(id): void {
    this.roleService.getRoleInfo(id).subscribe(
      data => {
        if (data.code === 2000) {
          this.roleInfo = data.data;
        }
      }
    );
  }

  /*角色添加*/
  addRoleSubmit(): void {
    this.roleService.addRole(this.addRole).subscribe(
      data => {
        if (data.code === 2000) {
          this.type = 'success';
          this.message = '添加成功';
          this.isShow = true;
          this.addModal.hide();
          this.getRoleList();
        }
      }
    );
  }

  /*角色修改*/
  editRoleSubmit(): void {
    this.editRole.id = this.roleInfo.id;
    this.editRole.name = this.roleInfo.name;
    this.editRole.slug = this.roleInfo.slug;
    this.editRole.description = this.roleInfo.description;
    this.editRole.level = this.roleInfo.level;
    this.editRole.belong = this.roleInfo.belong;
    this.roleService.editRole(this.editRole).subscribe(
      data => {
        if (data.code === 2000) {
          this.type = 'success';
          this.message = '修改成功';
          this.isShow = true;
          this.editModal.hide();
          this.getRoleList();
        }
      }
    );
  }

  num = 0;
  num1 = 1000;

  renderList(arr, data) {
    if (arr.length == 0) {
      arr.push({
        id: ++this.num,
        parentId: 0,
        isExpend: true,
        isChecked: false,
        name: data.model
      })
    } else {
      arr[arr.length - 1]['children'] = [];
      data.map((e, i) => {
        arr[arr.length - 1]['children'].push({
          id: ++this.num1,
          parentId: this.num,
          isExpend: true,
          isChecked: false,
          name: e.name
        })
      });
    }
    ;
    if (data.data) {
      let childNode = arr[arr.length - 1]['children'][arr[arr.length - 1]['children'].length - 1]['children'] = [];
      data.data.map((e, i) => {
        childNode.push({
          id: ++this.num,
          parentId: this.num1,
          isExpend: true,
          isChecked: false,
          name: e.name
        });
      });
      if (data.data.data) {
        this.renderList(arr[arr.length - 1]['children'], data.data.data);
      }
    }
  }

  getPermissionGroup(id) {
    this.setId = id;
    this.roleService.getPermissionGroup().subscribe(
      data => {
        if (data.code === 2000) {
          this.permissionGroup = data.data;
          this.p_list = [];
          this.permissionGroup.map((e, i) => {
            let data = e.data;
            this.p_list.push({
              id: ++this.num,
              parentId: 0,
              isExpend: true,
              isChecked: false,
              name: e.model
            });
            this.renderList(this.p_list, data);
            console.log('render_list', this.p_list);

            // this.p_list[this.p_list.length - 1]['children'] = [];
            // data.map((e1, i1) => {
            //   this.p_list[this.p_list.length - 1]['children'].push({
            //     id: ++this.num1,
            //     parentId: this.num,
            //     isExpend: true,
            //     name: e1.name,
            //   });
            //   this.p_list[this.p_list.length - 1]['children'][this.p_list[this.p_list.length - 1]['children'].length - 1]['children'] = [];
            //   this.p_list[this.p_list.length - 1]['children'][this.p_list[this.p_list.length - 1]['children'].length - 1]['children'].push({
            //     id: i1 + this.num1 * 1.5,
            //     parentId: this.num1,
            //     name: '哈哈哈'+e1.name,
            //     isChecked: true
            //   })
            // })
            // "id": "1",
            //   "parentId": "0",
            //   "name": "经典示例",
            //   "keyWord": "toast",
            //   "icon": 'fa-wrench',
            //   "isExpend": true,
            //   "isChecked": false,
            // checked: false
            // created_at: "2017-08-24 14:54:08"
            // deleted_at: null
            // description: "配置列表"
            // id: 1
            // model: "config"
            // name: "配置列表"
            // orderby: 1
            // slug: "config_list"
          });
          this.giveRolePermission(id);
        }
      }
    );
  }

  giveRolePermission(id) {
    this.roleService.getRolePermission(id).subscribe(
      data => {
        this.permissionCheck = data.data;
        this.permissionGroup.forEach(function (value, index, array) {
          value.data.forEach(function (value2, index2, array2) {
            value2.checked = true;
            if (data.data.indexOf(value2.id) === -1) {
              value2.checked = false;
            }
          });
        });
      }
    );
  }

  rolePermissionEdit(): void {
    const permission = JSON.stringify(this.permissionCheck);
    this.roleService.setRolePermission(permission, this.setId).subscribe(
      data => {
        if (data.code === 2000) {
          this.type = 'success';
          this.message = '修改成功';
          this.isShow = true;
          this.staticModal.hide();
          this.getRoleList();
        }
      }
    );
  }

  checkRolePermission(e, id) {
    if (e.target.checked) {
      this.permissionCheck.push(id);
    } else {
      for (let i = 0; i < this.permissionCheck.length; i++) {
        if (this.permissionCheck[i] === id) {
          this.permissionCheck.splice(i, 1);
          break;
        }
      }
    }
  };

  pageChanged(event: any): void {
    window.scrollTo(0, 0);
    this.currentPage = event.page;
    this.getRoleList();
  }

  promptIsShow(event: any): void {
    this.isShow = event;
  }
}
